package com.awspaas.user.apps.cpq.event;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.bpmn.engine.listener.ListenerConst;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONObject;

public class ModuleFormAfterSave extends ExecuteListener{

	@Override
	public void execute(ProcessExecutionContext pec) throws Exception {
		Workbook workbookwl = new XSSFWorkbook();
		try {
			String bindId=pec.getProcessInstance().getId();
			//BO表名
	        String boName = pec.getParameterOfString(ListenerConst.FORM_EVENT_PARAM_BONAME);
	        if(boName.equals("BO_EU_CPQ_MODULE_MSG")) {
	        	
	        	BO data=SDK.getBOAPI().query("BO_EU_CPQ_MODULE_MSG").bindId(bindId).detail();
	        	//List<BO> bos=(List) pec.getParameter(ListenerConst.FORM_EVENT_PARAM_GRIDDATA);
	        	List<BO> bos=SDK.getBOAPI().query("BO_EU_CPQ_MODULE_MSG_GRID").bindId(bindId).list();
	        	List<BO> list=SDK.getBOAPI().query("BO_EU_CPQ_MODULE_MSG_PRICE_PARAMETERS").bindId(bindId).list();
	        	String type=data.getString("CJLX");
	        	//获取模块中物料信息，对物料信息进行更新和计算，如果数量没有值，只更新物料信息；
	            String  wpsql="select  a.BM,a.NAME,a.TYPE,a.GG,a.TH,a.DW,a.ZL,a.TJ,"
	            		+ "a.CLF,"
	            		+ "a.RGF,a.WXWG,a.CGF,a.DJ,b.SL,b.ID "
	            		+ "from   BO_EU_CPQ_COMPONENT_PART a ,BO_EU_CPQ_MODULE_MSG_GRID b "
	            		+ "where  a.BM=b.WLBM and a.STATUS='启用' and b.BINDID=?";
	        	List<RowMap> maps=DBSql.getMaps(wpsql, new Object[] {bindId});
	        	Map<String, RowMap> newMap=new HashMap<String, RowMap>();	           
	            BigDecimal mkdj = new BigDecimal("0");	           
	            BigDecimal clf = new BigDecimal("0");	            
	            BigDecimal rgf = new BigDecimal("0");
	            BigDecimal wx = new BigDecimal("0");
	            BigDecimal cgf = new BigDecimal("0");
	            BigDecimal zl = new BigDecimal("0");
	            BigDecimal tj = new BigDecimal("0");
	         // 获取模块所需参数信息
    			Map<String, JSONObject> pMap = new HashMap<String, JSONObject>();
    			Map<String, String> nameMap = new HashMap<String, String>();
    			Map<String, String> noMap = new HashMap<>();
    			for (int i = 0; i < list.size(); i++) {
    				//JSONObject json = (JSONObject) list.get(i);
    				BO json = list.get(i);
    				String bh = (String) json.get("PARMENTIER_NO");
    				String value = (String) json.get("PARMENTIER_VALUE");
    				String name = (String) json.get("PARMENTIER_NAME");
    				String dw = (String) json.get("DW");
    				JSONObject jsonObject=new JSONObject();
    				//判断value是否为数据
    				if( NumberUtils.isCreatable(value)) {
    					jsonObject.put("type", "1");//值为1者表示value为数值
    				}else {
    					jsonObject.put("type", "0");//值为0者表示value为字符串
    				}
    				jsonObject.put("value", value);
    				pMap.put(bh, jsonObject);
    				nameMap.put(bh, name);
    				int num = i + 1;
    				noMap.put(bh, "B$" + num);
    			}
    			// 设置参数值到单元格中
    			Sheet sheet = workbookwl.createSheet("Sheet1");
    			for (int i = 0; i < list.size(); i++) {
    				int num = i + 1;
    				Cell cellB1 = sheet.createRow(i).createCell(1);
    				//JSONObject jsonObject = (JSONObject) list.get(i);
    				BO jsonObject =  list.get(i);
    				String bh = (String) jsonObject.get("PARMENTIER_NO");
    				JSONObject jsonObject2=	pMap.get(bh);
    				String type1=jsonObject2.getString("type");
    				if(type1.equals("0")) {
    					cellB1.setCellValue(jsonObject2.getString("value"));
    					System.out.println("cellB1:"+cellB1.getStringCellValue());
    				}else {
    					String value=jsonObject2.getString("value");
    					double  numValue=Double.parseDouble(value);		
    					 cellB1.setCellValue(numValue);
    					 System.out.println("cellB1:"+cellB1.getNumericCellValue());
    				}
    			}
	        	if(maps.size()>0) {
	        		for (RowMap rowMap : maps) {
						newMap.put(rowMap.getString("ID"), rowMap);
					}	        		
	        		//更新模块物料数据
	        		if(bos.size()>0) {
	        			List<BO> lists=new ArrayList<BO>();
	        			for (int i = 0; i < bos.size(); i++) {
	        				BO bo=bos.get(i);
							String bm=bo.getString("WLBM");
							String id=bo.getId();
							if(newMap.containsKey(id)) {
							RowMap rowMap=	newMap.get(id);
						    String NAME=rowMap.getString("NAME");
						    bo.set("WLMC", NAME);
						    String TYPE=rowMap.getString("TYPE");
						    bo.set("LX", TYPE);
						    String GG=rowMap.getString("GG");
						    bo.set("GG", GG);
						    String TH=rowMap.getString("TH");
						    bo.set("DH", TH);
						    String DW=rowMap.getString("DW");
						    bo.set("DW",DW );
						    String ZL=rowMap.getString("ZL");
						    bo.set("ZL", ZL);
						    String TJ=rowMap.getString("TJ");
						    bo.set("TJ", TJ);
						    String CLF=rowMap.getString("CLF");
						    bo.set("CLF", CLF);						   
						    String RGF=rowMap.getString("RGF");
						    bo.set("RGF",RGF );
						    String WXWG=rowMap.getString("WXWG");
						    bo.set("WXWG", WXWG);
						    String CGF=rowMap.getString("CGF");
						    bo.set("CGF",CGF );
						    String DJ=rowMap.getString("DJ");
						    bo.set("DJ", DJ);
						    String equation = bo.getString("WLJSGS");
							Document document = Jsoup.parse(equation);
							String newQuation=document.text();
							String SL=bo.getString("SL").isEmpty()?"0":bo.getString("SL");
							 BigDecimal num1 = new BigDecimal(SL);
							if (!newQuation.equals("0")&&!newQuation.isEmpty()) {
								// 获取物料数量计算公式中参数代号，如果有则将代号存放在list中
								for (String key : pMap.keySet()) {
									int num = newQuation.indexOf(key);
									if (num > -1) {
										newQuation = newQuation.replace(key, noMap.get(key));
									}
								}
								// 计算出物料数量和当前模块的物料成本价格
								FormulaEvaluator formulaEvaluator = workbookwl.getCreationHelper().createFormulaEvaluator();
								Cell cellB1 = sheet.createRow(list.size()+i).createCell(2);
								cellB1.setCellFormula(newQuation);
								formulaEvaluator.evaluateFormulaCell(cellB1);
								// 获取公式计算结果
								CellValue cellValue = formulaEvaluator.evaluate(cellB1);
								//System.out.println("The result of the formula is: " + cellValue.getNumberValue());
								 BigDecimal num2 = new BigDecimal(cellValue.getNumberValue());
								 num1=num2;
							}
						  
						   // System.out.println("数量："+SL);
						  //  System.out.println("数量bo："+bo.getString("SL"));
						    	// BigDecimal num1 = new BigDecimal(SL);
						    	 if(null!=ZL&&!ZL.isEmpty()) {
									 BigDecimal num3 = new BigDecimal(ZL);
									 zl=zl.add(num1.multiply(num3));
									bo.set("ZZL", num1.multiply(num3));
								}else {
									bo.set("ZZL", "0");
								}
								if(null!=TJ&&!TJ.isEmpty()) {
									 BigDecimal num3 = new BigDecimal(TJ);
									 tj=tj.add(num1.multiply(num3));
									bo.set("ZTJ", num1.multiply(num3));
								}else {
									bo.set("ZTJ", "0");
								}
								if(null!=CLF&&!CLF.isEmpty()) {
									 BigDecimal num3 = new BigDecimal(CLF);
									 clf=clf.add(num1.multiply(num3));
									bo.set("ZCLF", num1.multiply(num3));
								}else {
									bo.set("ZCLF", "0");
								}
								
								
								if(null!=RGF&&!RGF.isEmpty()) {
									 BigDecimal num3 = new BigDecimal(RGF);
									 rgf=rgf.add(num1.multiply(num3));
									bo.set("ZGSF", num1.multiply(num3));
								}else {
									bo.set("ZGSF", "0");
								}
								if(null!=WXWG&&!WXWG.isEmpty()) {
									 BigDecimal num3 = new BigDecimal(WXWG);
									 wx=wx.add(num1.multiply(num3));
									bo.set("ZWX", num1.multiply(num3));
								}else {
									bo.set("ZWX", "0");
								}
								if(null!=CGF&&!CGF.isEmpty()) {
									 BigDecimal num3 = new BigDecimal(CGF);
									 cgf=cgf.add(num1.multiply(num3));
									bo.set("ZCGF", num1.multiply(num3));
								}else {
									bo.set("ZCGF", "0");
								}
								if(null!=DJ&&!DJ.isEmpty()) {
									 BigDecimal num3 = new BigDecimal(DJ);
									 mkdj=mkdj.add(num1.multiply(num3));
									bo.set("ZJ", num1.multiply(num3));
								}else {
									bo.set("ZJ", "0");
								}
								
						    System.out.println("更新的物料信息："+bo.toString());
						    SDK.getBOAPI().update("BO_EU_CPQ_MODULE_MSG_GRID", bo);
							}
						}
	        			
	        			
	    	        	
	        		}
	        	}
	        	//获取直发物资运费
	        	List<BO> zfs=SDK.getBOAPI().query("BO_EU_BO_EU_CPQ_MODULE_MSG_STRAIGHT_HAIR").bindId(bindId).list();
	        	 BigDecimal ZFYF = new BigDecimal("0");	   
	        	 List<String> sqlLists=new ArrayList<>();
	        	if(zfs.size()>0) {
	        		for (int i = 0; i < zfs.size(); i++) {
	        			  BO bo2=zfs.get(i);	
	        			String sljsgs=bo2.getString("JSGS");//直发运费数量计算公式；
	        			String yfdj=bo2.getString("YFBZ").isEmpty()?"0":bo2.getString("YFBZ");//运费单价；
	        			String SL=bo2.getString("SL").isEmpty()?"0":bo2.getString("SL");//运费单价；
	        			 BigDecimal price = new BigDecimal(yfdj);	
	        			 BigDecimal sl = new BigDecimal(SL);
					    ZFYF=ZFYF.add(price.multiply(sl));
					    Document document = Jsoup.parse(sljsgs);
						String newQuation=document.text();
						 if (!newQuation.equals("0")&&!newQuation.isEmpty()) {
							  for (String key : pMap.keySet()) {
									int num = newQuation.indexOf(key);
									if (num > -1) {
										newQuation = newQuation.replace(key, noMap.get(key));
									}
								}
							  FormulaEvaluator formulaEvaluator = workbookwl.getCreationHelper().createFormulaEvaluator();
								Cell cellB1 = sheet.createRow(list.size()+bos.size()+2+i).createCell(2);
								cellB1.setCellFormula(newQuation);
								formulaEvaluator.evaluateFormulaCell(cellB1);
								// 获取公式计算结果
								CellValue cellValue = formulaEvaluator.evaluate(cellB1);
								System.out.println("The result of the formula is: " + cellValue.getNumberValue()); 
								BigDecimal num = new BigDecimal(cellValue.getNumberValue());
								ZFYF=ZFYF.add(num.multiply(price));
								 String upSql= "update BO_EU_CPQ_MODULE_RECORD_STRAIGHT_HAIR set SL= '"+cellValue.getNumberValue()+"',YFJG= '"+num.multiply(price)+"'  where ID='"+bo2.getString("ID")+"' ; ";
									//upSql=String.format(upSql, cldjNew,clfNew,zjNew,zclfNew,ID);
									sqlLists.add(upSql);

					}else {
						//String sl=bo2.getString("SL").isEmpty()?"0":bo2.getString("SL");//运费数量;
						 //double num=Double.parseDouble(sl);
						//ZFYF=ZFYF+num*price;
						ZFYF=ZFYF.add(sl.multiply(price));
					}   
					    
					}
	        	}
	        	mkdj=mkdj.add(ZFYF);
	        	 String bl=data.getString("ZZFBL").isEmpty()?"0":data.getString("ZZFBL");		    					
					BigDecimal blnum = new BigDecimal(bl);
					BigDecimal num2 = new BigDecimal("100");
					BigDecimal num1 = new BigDecimal("1");
					BigDecimal zzf=	clf.add(rgf).divide(num1.subtract(blnum.divide(num2)), 4).multiply(blnum.divide(num2));
	        	data.set("MKDJ", mkdj);	        			
	        	data.set("CLF",clf);	    	        	
	        	data.set("RGF", rgf);
	        	data.set("WXWG", wx);
	        	data.set("CGF", cgf);
	        	data.set("ZFWZYF", ZFYF);
	        	data.set("ZZF", zzf);
	        	data.set("DJZZF", zzf.add(mkdj));
	        	if(sqlLists.size()>0) {
					 String[] array3 = sqlLists.toArray(new String[sqlLists.size()]);	
					 DBSql.batch(array3);
				}
	        	System.out.println("模块单价"+mkdj);
	        	if(type.equals("创建新版本")) {
	        		String mkbm=data.getString("MKBM");
	        		SimpleDateFormat sdftime = new SimpleDateFormat("yyyy-MM-dd");
	        		long newtime = new Date().getTime();// 创建时间
					String timestamp=sdftime.format(new Date(newtime));
	        		String sql="Update BO_EU_CPQ_MODULE_MSG set STATUS='停用', TYSJ='"+timestamp+"' where MKBM='"+mkbm+"' and STATUS='启用'";
	        		DBSql.update(sql);
	        		data.set("STATUS", "启用");
		        	data.set("CJLX", "");		        	
		        	SDK.getBOAPI().update("BO_EU_CPQ_MODULE_MSG", data);
	        	}else if (type.equals("创建新模块")) {
	        		data.set("STATUS", "启用");
		        	data.set("CJLX", "");
		        	SDK.getBOAPI().update("BO_EU_CPQ_MODULE_MSG", data);
				}
	        	
	        	
	        	
	        	
	        }
	        
	        
	        
	        
		} catch (Exception e) {
			throw e;
		}
		
	}

}
